package com.augurit.wf.jbpmex.cmd;

import java.util.Date;

import org.jbpm.api.JbpmException;
import org.jbpm.api.cmd.Environment;
import org.jbpm.pvm.internal.cal.BusinessCalendar;
import org.jbpm.pvm.internal.cmd.AbstractCommand;
import org.jbpm.pvm.internal.env.EnvironmentImpl;


public class CalculateDueDateCmd extends AbstractCommand<Date>{

	private static final long serialVersionUID = 1L;
	
	private Date startDate;
	private String durationExpression;
	
	public CalculateDueDateCmd(Date startDate,String durationExpression){
		this.startDate = startDate;
		this.durationExpression = durationExpression;
	}
	
	public Date execute(Environment environment) throws Exception {
		Date duedate = null;
	    if (durationExpression != null) {

	      char durationSeparator = '+'; // needs to be initialized

	      if (durationExpression == null || durationExpression.length() == 0) {
	        duedate = startDate;
	      } else {
	        if (durationExpression.contains("business") && durationSeparator == '-') {
	          throw new JbpmException("Invalid duedate, subtraction ('-') not supported if duedate contains 'business'");
	        }
	        BusinessCalendar businessCalendar = EnvironmentImpl.getFromCurrent(BusinessCalendar.class);
	        if (durationSeparator == '+') {
	          duedate = businessCalendar.add(startDate, durationExpression);
	        } else {
	          duedate = businessCalendar.subtract(startDate, durationExpression);
	        }
	      }
	    }
	    return duedate;
	}
}